package com.controller;

//预约业务处理

import com.alibaba.dubbo.config.annotation.Reference;
import com.aliyuncs.exceptions.ClientException;
import com.constant.MessageConstant;
import com.constant.RedisMessageConstant;
import com.entity.Result;
import com.pojo.Order;
import com.service.OrderService;
import com.utils.SMSUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Map;

@RestController
@RequestMapping("/order")
public class OrderController {
    
    @Autowired
    private JedisPool jedisPool;

    @Reference
    private OrderService orderService;

    @RequestMapping("/submit")
    public Result submit(@RequestBody Map map){
        //进行验证码的校验 判断用户输入的验证码是否与redis中存入的验证码是否一样
        //获取用户输入的手机号码
        String telephone = (String) map.get("telephone");
        //获取rdeis中存入的验证码
        String validateCodeInRdeis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_ORDER);
        //获取用户输入的验证码
        String validateCode = (String) map.get("validateCode");
        if (validateCodeInRdeis != null && validateCode != null && validateCodeInRdeis.equals(validateCode)){
            //设置预约类型， 有微信预约 和 电话预约
            map.put("orderType", Order.ORDERTYPE_WEIXIN);
            Result result = null;
            try {
                //预约成功 调用服务预约成功处理
                result = orderService.order(map);
            } catch (Exception e) {
                //预约失败
                e.printStackTrace();
                return result;
            }
            //判断是否预约成功
            if (result.isFlag()){
                //预约成功
                String orderDate = (String) map.get("orderDate");
                try {
                    //发送短信提醒客户预约成功
                    SMSUtils.sendShortMessage(SMSUtils.ORDER_NOTICE,telephone,orderDate);
                } catch (ClientException e) {
                    e.printStackTrace();
                }
            }
            return result;
        } else {
            //预约失败
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
    }

    //通过订单id查询体检人，体检套餐，体检时间，预约类型
    @RequestMapping("/findById")
    public Result findById(Integer id){
        try {
            Map map = orderService.findById(id);
            return new Result(true,MessageConstant.QUERY_ORDER_SUCCESS,map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_ORDER_FAIL);
        }
    }
}
